package com.example.piemapdemo;

import static com.pie.uitls.ConfigPathConstant.DataSourceFilePath.MAPBOX_PATH;

import android.Manifest;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.pie.map.Base.Size2d;
import com.pie.map.Base.Vector2d;
import com.pie.map.DependOnLayerType;
import com.pie.map.Document.Workspace;
import com.pie.map.Globe.Layer.MapboxLayer;
import com.pie.map.Globe.SceneMode;
import com.pie.map.Overlay.BaseOverlay;
import com.pie.map.Overlay.options.OverlayCircleOption;
import com.pie.map.Overlay.options.OverlayLineOption;
import com.pie.map.Overlay.options.OverlayPointOption;
import com.pie.map.Overlay.options.OverlayRegionOption;
import com.pie.map.Overlay.options.OverlayTextOption;
import com.pie.map.PieMap;
import com.pie.map.Style.TextStyle;
import com.pie.map.Style.VectorStyle;
import com.pie.view.MapViews;
import com.piesat.license.LicenseExternalVerifyTool;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    private String TAG = "MainActivity";
    private static final int REQUEST_CODE_PERMISSION = 1;
    @BindView(R.id.mMapView)
    MapViews mapView;

    private PieMap pieMap;
    private Bitmap locBitmap;
    private String commonOverlayName = "commonOverlayName";

    //地图放大
    @OnClick(R.id.btn_zoom_in)
    public void onZoomIn() {
        pieMap.zoomIn();
    }

    //地图缩小
    @OnClick(R.id.btn_zoom_out)
    public void onZoomOut() {
        pieMap.zoomOut();
    }

    //设置地图中心点
    @OnClick(R.id.iv_location)
    public void onSetLocation() {
        pieMap.setMapCenter(new Vector2d(116.229225, 39.952858));
    }

    //设置地图范围
    @OnClick(R.id.btn_set_bounds)
    public void onBoundsClick() {
        List<Vector2d> vector2ds = new ArrayList<>();
        vector2ds.add(new Vector2d(116.229225, 39.952858));
        vector2ds.add(new Vector2d(118.229225, 39.952858));
        vector2ds.add(new Vector2d(118.229225, 36.952858));
        pieMap.setViewBounds(vector2ds);

    }

    //设置地图模式
    @OnCheckedChanged(R.id.cb_map_mode)
    public void onMapModeChange(boolean isChecked) {
        setMapSceneMode(isChecked ? SceneMode.PlaneMode : SceneMode.SphereMode);
    }

    //切换地图模式
    public void setMapSceneMode(SceneMode sceneMode) {
        //2d模式
        if (sceneMode == SceneMode.PlaneMode) {
            pieMap.setSceneMode(SceneMode.PlaneMode);
            pieMap.setPitchAngle(0);
            pieMap.setMaxPitchAngle(0);
            pieMap.setRotate(false);
            pieMap.setRollAngle(0);
            //3d模式
        } else if (sceneMode == SceneMode.SphereMode) {
            pieMap.setSceneMode(SceneMode.SphereMode);
            pieMap.setMaxPitchAngle(90);
            pieMap.setPitchAngle(5);
            pieMap.setRotate(true);
        }

        Log.e(TAG, "setMapSceneMode: " + pieMap.getMaxPitchAngle());
    }

    //添加点
    @OnClick(R.id.btn_add_point)
    public void onAddPoint() {
        OverlayPointOption pointOptions = new OverlayPointOption.Builder()
                .pointSize(new Size2d(85, 85))
                .icon(locBitmap)
                .pointAlign(VectorStyle.PointAlignType.PAT_Center)
                .point(new Vector2d(114.229225, 39.952858))
                .tag("tag")
                .overLayName(commonOverlayName)
                .pointType(VectorStyle.PointType.PT_Icon)
                .build();
        pieMap.addOverlay(pointOptions, null);
    }

    //添加线
    @OnClick(R.id.btn_add_line)
    public void onAddLine() {
        String commonOverlayName = "commonOverlayName";
        List<Vector2d> vector2ds = new ArrayList<>();
        vector2ds.add(new Vector2d(116.229225, 39.952858));
        vector2ds.add(new Vector2d(118.229225, 39.952858));
        vector2ds.add(new Vector2d(118.229225, 36.952858));
        OverlayLineOption lineOptions = new OverlayLineOption.Builder()
                .lineColor(Color.BLUE)
                .lineWidth(3)
                .points(vector2ds)
                .overLayName(commonOverlayName)
                .tag("tag")
                .build();
        pieMap.addOverlay(lineOptions, null);
    }

    //添加面
    @OnClick(R.id.btn_add_region)
    public void onAddRegion() {
        String commonOverlayName = "commonOverlayName";
        List<Vector2d> vector2ds = new ArrayList<>();
        vector2ds.add(new Vector2d(116.229225, 39.952858));
        vector2ds.add(new Vector2d(118.229225, 39.952858));
        vector2ds.add(new Vector2d(118.229225, 36.952858));
        OverlayRegionOption regionOptions = new OverlayRegionOption.Builder()
                .points(vector2ds)
                .foreFillColor(Color.BLUE)
                .strokeLineColor(Color.RED)
                .strokeLineWidth(5)
                .tag("tag")
                .overLayName(commonOverlayName)
                .build();
        pieMap.addOverlay(regionOptions, null);
    }

    //添加圆
    @OnClick(R.id.btn_add_circle)
    public void onAddCircle() {
        String commonOverlayName = "commonOverlayName";
        OverlayCircleOption circleOption = new OverlayCircleOption.Builder()
                .foreFillColor(Color.BLUE)
                .circleCenter(new Vector2d(116.229225, 39.952858))
                .radius(1000000)
                .strokeLineColor(Color.RED)
                .strokeLineWidth(5)
                .overLayName(commonOverlayName)
                .tag("tag")
                .build();
        pieMap.addOverlay(circleOption, DependOnLayerType.LAYER_TYPE_GRAPHICS);
    }

    //清除图层
    @OnClick(R.id.btn_clear)
    public void onClearOverlay() {
        pieMap.removeOverlayByOverlayName(commonOverlayName);
    }

    //设置指南针显隐
    @OnCheckedChanged(R.id.cb_compass)
    public void onShowCompass(boolean isShow) {
        pieMap.setCompassOffset(0, 220, 0, 0);
        pieMap.setCompassVisible(isShow);
    }

    //设置比例尺显隐
    @OnCheckedChanged(R.id.cb_scale_ratio)
    public void onShowScale(boolean isShow) {
        pieMap.setScaleRatioVisible(isShow);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLic();
        checkPermission();
    }

    private void initLic() {
        String content = getStringFromAssets(this, "license.lic");
        LicenseExternalVerifyTool.content = content;
        LicenseExternalVerifyTool.get().registerLicense();
    }

    private void initViews() {
        if (initWorkspace()) {
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
            pieMap = mapView.getPieMap();
            openMapBox();
            initData();
            initEvents();
        } else {
            Log.e("openMapBox", "工作空间打开失败，请确认配置是否正确！");
        }
    }

    private void initData() {
        locBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_marker);
    }

    private void initEvents() {
        //地图点击事件监听
        pieMap.setOnMapClickListener(vector2d -> {
            Log.e(TAG, "onMapClick: " + vector2d.toString());
        });

        //地图长按事件监听
        pieMap.setOnMapLongClickListener(vector2d -> {
            Log.i(TAG, "onMapLongClick: " + vector2d.toString());
        });

        //地图平移事件监听
        pieMap.setOnMapPanListener(new PieMap.OnMapPanListener() {
            @Override
            public void onPan(Vector2d vector2d, Vector2d vector2d1) {
                Log.i(TAG, "onPan: 起点：" + vector2d.toString() +
                        "--终点：" + vector2d1.toString());
            }

            @Override
            public void onPanStop() {
                Log.i(TAG, "onPanStop: 平移结束");
            }
        });

        //地图旋转事件监听
        pieMap.setOnMapRotateChangedListener(angel -> {
            Log.i(TAG, "onRotateChanged:" +
                    String.format("旋转角度：%s", angel));
        });

        pieMap.setMapPitchChangedListener(angel -> {
            Log.i(TAG, "onPitchChanged:" +
                    String.format("俯仰角度：%s", angel));
        });

        pieMap.setOnMapScaleChangeListener(angel -> {
            Log.i(TAG, "onScaleChanged:" +
                    String.format("缩放比例：%s", angel));
        });

        pieMap.setOnMapCenterChangeListener(vector2d -> {
            Log.i(TAG, "onMapCenterChange:" + vector2d.toString());
        });

        pieMap.setOnOverlayClickListener(baseOverlay -> {
            Log.i(TAG, "onOverlayClick: " + baseOverlay.toString());
        });

        pieMap.setOnOverlayClickListener(new PieMap.OnOverlayClickListener() {
            @Override
            public void onOverlayClick(BaseOverlay baseOverlay) {
                Log.i(TAG, "onOverlayClick: ");
            }
        });

    }


    private void openMapBox() {
        boolean isOpened = pieMap.openMap("GoogleImageScene", null);
        if (!isOpened) {
            Log.e("openMapBox", "地图打开失败，请确认地图配置是否正确！");
            return;
        }
    }


    private void addMapboxLayerByStyle(String style) {
        MapboxLayer mapboxLayer = new MapboxLayer();
        mapboxLayer.setStyleURL(style, MAPBOX_PATH);
        mapboxLayer.setName("MapBoxLayer");
        mapboxLayer.setVisible(true);
        pieMap.addLayer(mapboxLayer, true);
    }

    private boolean initWorkspace() {
        String workSpacePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/eData/PIE/mapconfig";
        String dataPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/eData//PIEMap";
        Workspace.init(workSpacePath, dataPath);
        String WORK_XML_PATH = workSpacePath + "/Workspace.wkp";
        return Workspace.open(WORK_XML_PATH);
    }

    private void checkPermission() {
        String[] permissions = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        ActivityCompat.requestPermissions(this, permissions,
                REQUEST_CODE_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions,
                grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            for (int grant : grantResults) {
                if (grant != 0) {
                    Toast.makeText(this,
                            "部分权限未开启,可能会影响正常功能！",
                            Toast.LENGTH_LONG).show();
                    break;
                }
            }
            initViews();
        }
    }

    private String getStringFromAssets(Context context, String fileName) {
        String str = "";
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(context.getAssets().open(fileName), "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while (!TextUtils.isEmpty(line = bufferedReader.readLine())) {
                stringBuilder.append(line);
                stringBuilder.append("\n");
            }
            bufferedReader.close();
            inputStreamReader.close();
            str = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }


}